<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      title="维保商资产"
      :need-return="false"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>
            {{ $t('basic_information') }}
          </p>
        </div>
        <div class="model-panel-body" style="padding: 10px 0px 13px 0px">
          <basic-information
            :info="infoList"
            :rules="infoList.rules"
            v-model:ref-obj="infoList.ref"
          >
            <template v-slot:basic-contact>
              <el-input
                v-model="infoList.data.contact"
                type="text"
                placeholder="联系人"
                @input="(e) => (infoList.data.contact = validSe(e))"
              />
            </template>
            <template v-slot:basic-contactNumber>
              <el-input
                v-model="infoList.data.contactNumber"
                type="text"
                placeholder="联系电话"
                @input="(e) => (infoList.data.contactNumber = validSe(e))"
              />
            </template>
            <template v-slot:basic-serviceScope>
                <el-select
                  v-model="infoList.data.serviceScope"
                  placeholder="请选择服务范围"
                  disabled
                  collapse-tags
                  style="width: 300px"
                >
                  <el-option
                    v-for="(item, index) in serviceScopeList"
                    :key="index"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </template>
          </basic-information>
        </div>
      </div>
      <!--返回了orgType用这个<div class="model-panel" v-if="tableRow.orgType && tableRow.orgType.includes('supplier')">-->
      <!-- <div v-if="tableRow.orgType && tableRow.orgType.includes('supplier')" class="model-panel"> -->
      <div v-if="0" class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('product_list') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <PageFilter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct()"
                >删除资产</el-button
              >
            </template>
            <!--            <template v-slot:filter-uploadProduct="scope">-->
            <!--              <el-upload-->
            <!--                :headers="uploadInfo.headers"-->
            <!--                :show-file-list="false"-->
            <!--                :data="uploadInfo.data"-->
            <!--                :on-success="importProduct"-->
            <!--                :before-upload="beforeProductUpload"-->
            <!--                :action="uploadInfo.action"-->
            <!--              >-->
            <!--                <el-button>导入资产</el-button>-->
            <!--              </el-upload>-->
            <!--            </template>-->
          </PageFilter>
          <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
            <PageTable
              :refresh="tableInfo.refresh"
              :init-curpage="tableInfo.initCurpage"
              v-model:data="tableInfo.data"
              :api="tableInfo.api"
              :pager="true"
              v-model:query="filterInfo.query"
              :field-list="tableInfo.fieldList"
              :handle="tableInfo.handle"
              :isDynamic="true"
              @handleEvent="handleEvent"
            >
              <template v-slot:col-licenseNumber="scope">
                <p>{{ scope.row.licenseNumber || '-' }}</p>
                <p>{{ scope.row.brandName || '-' }}</p>
              </template>
              <template v-slot:col-commonName="scope">
                <p>{{ scope.row.commonName || '-' }}</p>
                <p>{{ scope.row.productCode || '-' }}</p>
                <p>{{ scope.row.alias || '-' }}</p>
              </template>
              <template v-slot:col-type="scope">
                <p>{{ scope.row.productTypeValue || '-' }}</p>
                <p>{{ scope.row.codeTypeValue || '-' }}</p>
                <p>{{ scope.row.productCategoryValue || '-' }}</p>
              </template>
              <template v-slot:col-standard="scope">
                <p>{{ scope.row.standard || '-' }}</p>
                <p>{{ scope.row.unitName || '-' }}</p>
              </template>
              <template v-slot:col-price="scope">
                <el-form-item
                  v-if="scope.row.edit"
                  :prop="`data.${scope.$index}[price]`"
                  :rules="
                    scope.$index >= 0
                      ? [{ validator: $validate.positive, trigger: 'blur' }]
                      : []
                  "
                >
                  <el-input
                    v-model.number.trim="scope.row.price"
                    type="number"
                    style="width: 100px"
                    :precision="2"
                    :min="0"
                    :max="99999999"
                  />
                </el-form-item>
                <p v-else>{{ $fn.TripartiteMethod(scope.row.price) }}</p>
              </template>
            </PageTable>
          </el-form>
        </div>
      </div>
      <!--返回了orgType用这个<div class="model-panel" v-if="tableRow.orgType && tableRow.orgType.includes('maintenance')">-->
      <div
        v-if="tableRow.orgType && tableRow.orgType.includes('maintenance')"
        class="model-panel"
      >
        <div class="model-panel-title">
          <p>资产信息</p>
        </div>
        <div class="model-panel-body">
          <PageFilter
            v-model:query="filterEquipmentInfo.query"
            :filter-list="filterEquipmentInfo.list"
          >
            <template v-slot:filter-removeEquipment>
              <el-button
                :disabled="!canRemoveEquipment"
                @click="removeEquipment()"
                >删除资产</el-button
              >
            </template>
          </PageFilter>
          <PageTable
            :refresh="tableEquipmentInfo.refresh"
            :init-curpage="tableEquipmentInfo.initCurpage"
            v-model:data="tableEquipmentInfo.data"
            :api="tableEquipmentInfo.api"
            v-model:query="filterEquipmentInfo.query"
            :field-list="tableEquipmentInfo.fieldList"
            :handle="tableEquipmentInfo.handle"
            :isDynamic="true"
            @handleEvent="handleEventEquipment"
          >
            <template v-slot:col-commonName="scope">
              <p>{{ scope.row.commonName || '-' }}</p>
              <p>{{ scope.row.code || '-' }}</p>
            </template>
            <template v-slot:col-unitName="scope">
              <p>{{ scope.row.unitName || '-' }}</p>
              <p>{{ scope.row.standard || '-' }}</p>
            </template>
            <template v-slot:col-brandName="scope">
              <p>{{ scope.row.trademark || '-' }}</p>
              <p>{{ scope.row.brandName || '-' }}</p>
            </template>
            <template v-slot:col-deviceTypeValue="scope">
              <p>{{ scope.row.deviceTypeValue || '-' }}</p>
              <p>{{ scope.row.financeTypeValue || '-' }}</p>
            </template>
          </PageTable>
        </div>
      </div>
    </NewFullScreen>
    <!-- 资产弹窗 -->
    <SelectProductAddPrice
      v-if="productInfo.visible"
      v-model:query="productInfo.query"
      v-model:show-dialog="productInfo.visible"
      @callback="selectProduct"
    />
    <!-- 资产弹窗 -->
    <SelectEquipmentArchives
      v-if="equipmentInfo.visible"
      v-model:show-dialog="equipmentInfo.visible"
      v-model:query-params="equipmentInfo.queryParams"
      @callback="changeEquipment"
    />
  </div>
</template>

<script setup name="maintenanceProduct">
import BasicInformation from '@/components/BasicInformation/index'
import SelectEquipmentArchives from '@/components/SelectEquipmentArchives/index'
import {
  getMaintenanceProductPage,
  batchCreateMaintenanceProduct,
  deleteMaintenanceProduct,
  getSupplierProductPage,
  batchCreateSupplierProduct,
  updateMaintenance,
  exportMaintenanceProduct,
  exportSupplierProduct,
  deleteSupplierProduct,
} from '@/api/core.js'
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
const emits = defineEmits()
const store = useStore()
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: true,
  },
  tableRow: {
    type: Object,
    default: function () {
      return {}
    },
  },
})
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/core/supplierProducts/import/excel',
  deviceAction:
    axios.defaults.baseURL + '/mapping/mappingSupplierDevice/import/excel',
  headers: {
    Authorization: store.state.user.token,
  },
  loading: {},
  data: {
    supplierId: props.tableRow.supplierId,
  },
})
const infoList = ref({
  ref: null,
  data: props.tableRow,
  fieldList: [
    { label: '维保商名称', value: 'maintenanceName', type: 'text' },
    { label: '联系人', value: 'contact', type: 'slot' },
    { label: '联系电话', value: 'contactNumber', type: 'slot' },
    { label: '服务范围', value: 'serviceScope', type: 'slot' },
    { label: '状态', value: 'orgStatusValue' },
  ],
  rules: {
    contactNumber: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    searchType: 'product',
    searchField: 'productId',
    showDisabled: true,
    supplierId: props.tableRow.maintenanceId,
    sort: 'create_time desc',
  },
  list: [
    {
      type: 'button',
      label: '添加资产',
      event: addProduct,
      disabled: props.tableRow.orgStatus === 0,
    },
    { type: 'slot', value: 'removeProduct' },
    {
      type: 'button',
      label: '导出资产',
      event: exportExcel,
      disabled: false,
    },
    // { type: "slot", value: "uploadProduct" },
    {
      type: 'input',
      label: '名称/别名/编码/助记符',
      value: 'keyword',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: getSupplierProductPage,
  data: [],
  selections: [],
  fieldList: [
    { label: '证号\n生产厂家', value: 'licenseNumber', type: 'slot' },
    { label: '通用名称\n编码\n别名', value: 'commonName', type: 'slot' },
    {
      label: '资产类型\n条码类型\n资产分类',
      value: 'type',
      type: 'slot',
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    { label: '价格', value: 'price', type: 'slot' },
    // {label: '状态', value: 'statusValue'}
  ],
})
const fullInfo = ref({
  btnList: [
    { label: '保存', event: saveInformation, show: true },
    { label: '返回', event: returnBack, show: true },
  ],
})
//资产弹窗相关
const productInfo = ref({
  query: {},
  visible: false,
})
const filterEquipmentInfo = ref({
  query: {
    searchType: 'equipmentArchives',
    searchField: 'productId',
    maintenanceId: props.tableRow.maintenanceId,
  },
  list: [
    { type: 'button', label: '添加资产', event: addEquipment },
    { type: 'slot', value: 'removeEquipment' },
    {
      type: 'button',
      label: '导出资产',
      event: exportEquipmentExcel,
      disabled: false,
    },
    {
      type: 'input',
      label: '名称/编码',
      value: 'keyword',
      event: searchDevice,
    },
    { type: 'button', label: '搜索', event: searchDevice },
  ],
})
const tableEquipmentInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: getMaintenanceProductPage,
  selections: [],
  fieldList: [
    { label: '资产名称\n编码', value: 'commonName', type: 'slot' },
    { label: '计量单位\n资产规格', value: 'unitName', type: 'slot' },
    { label: '医疗器械分类目录\n财务类别', value: 'deviceTypeValue', type: 'slot' },
    { label: '品牌\n生产厂家', value: 'brandName', type: 'slot' },
    { label: '资产图片', value: 'picture', type: 'showImage' },
  ],
})
const equipmentInfo = ref({
  visible: false,
  query: {},
  queryParams: {
    maintenanceId: props.tableRow.maintenanceId,
  },
})
const serviceScopeList = computed(() => {
  return proxy.$store.state.permission.dict['service_scope'] || []
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    // 更新父组件visible
    emits('update:visible', val)
  },
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})
const canRemoveEquipment = computed(() => {
  return tableEquipmentInfo.value.selections.length
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (!val.length) {
      filterInfo.value.list[2].disabled = true
    } else {
      filterInfo.value.list[2].disabled = false
    }
  }
)

function returnBack() {
  showDialog.value = false
  proxy.$emit('returnBack')
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function getEquipmentList() {
  tableEquipmentInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 搜索资产
function searchDevice() {
  tableEquipmentInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function handleEventEquipment(event, data) {
  switch (event) {
    case 'tableCheck':
      tableEquipmentInfo.value.selections = [...data]
      break
  }
}
function saveInformation() {
  //修改基础信息
  let data = Object.assign({}, props.tableRow)
  data.contactNumber = infoList.value.data.contactNumber
  data.serviceScope = infoList.value.data.serviceScope
  data.contact = infoList.value.data.contact
  data.serviceScopeValue = ''
  let arr = []
  serviceScopeList.value.map((item, index) => {
    if (infoList.value.data.serviceScope == item.code) {
      arr.push(item.name)
    }
  })
  data.serviceScopeValue = arr.join(',')
  infoList.value.ref.validate((valid) => {
    if (valid) {
      updateMaintenance(data).then((resp) => {
        if (resp && resp.success) {
          showDialog.value = false
          emits('callback', null)
        }
      })
    }
  })
}
//添加资产按钮
function addProduct() {
  const idNotIn = tableInfo.value.data.map(function (item) {
    return item.productId
  })
  productInfo.value.query.idNotIn = idNotIn.toString()
  productInfo.value.query.supplierId = infoList.value.data.maintenanceId
  productInfo.value.visible = true
}
//选择资产回调
function selectProduct(data = []) {
  let arr = data.map(function (item) {
    return {
      ...item,
      productId: item.id,
      edit: false,
    }
  })
  save(arr)
}
function save(data) {
  proxy.$refs['tableForm'].validate((valid) => {
    if (valid) {
      const _tableInfo = tableInfo.value
      const supplierId = infoList.value.data.maintenanceId
      data = data.map(function (item) {
        return {
          productId: item.productId,
          supplierId: supplierId,
          status: 'confirmed',
          price: item.price,
          isLimitPrice: item.isLimitPrice,
          purchaseLimitPrice: item.purchaseLimitPrice,
        }
      })

      if (!data || !data.length) {
        return
      }

      batchCreateSupplierProduct(data).then((resp) => {
        if (resp && resp.success) {
          _tableInfo.refresh = Math.random()
        }
      })
    }
  })
}

//删除资产
function removeProduct() {
  const ids = tableInfo.value.selections.map((value) => value.id)
  if (ids.length) {
    proxy.$handleAPI('delete', deleteSupplierProduct, ids).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    proxy.$message({
      type: 'warning',
      message: '请选择资产！',
      duration: 3500,
      showClose: true,
    })
  }
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  return true
}
function importProduct(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function importDevice(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg.replace(/[\n]/g, '\\n'),
    })
    getEquipmentList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function addEquipment() {
  equipmentInfo.value.visible = true
}
function changeEquipment(data) {
  equipmentInfo.value.visible = false
  if (data && data.length) {
    let arr = data.map((item) => {
      return {
        productId: item.id,
        maintenanceId: props.tableRow.maintenanceId,
      }
    })
    batchCreateMaintenanceProduct(arr).then((res) => {
      if (res) {
        getEquipmentList()
      }
    })
  }
}
function removeEquipment() {
  if (tableEquipmentInfo.value.selections.length) {
    let arr = []
    arr = tableEquipmentInfo.value.selections.map((item) => item.id)
    deleteMaintenanceProduct(arr).then((res) => {
      if (res) {
        getEquipmentList()
      }
    })
  } else {
    proxy.$message({
      type: 'warning',
      message: '请选择资产！',
      duration: 3500,
      showClose: true,
    })
  }
}
function exportExcel() {
  exportSupplierProduct(props.tableRow.maintenanceId).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function exportEquipmentExcel() {
  exportMaintenanceProduct(props.tableRow.maintenanceId).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

onMounted(() => {
  proxy.$nextTick(() => {
    if (props.tableRow.serviceScope) {
      infoList.value.data.serviceScope = props.tableRow.serviceScope == -2 ? '' : props.tableRow.serviceScope + ''
    }
    getList()
    getEquipmentList()
  })
})
</script>

<style scoped>
.right-btn {
  float: right;
  margin-right: 10px;
}
</style>
